<template>
  <div style="padding: 20px">
    <el-input v-model="toUserId" placeholder="接收用户ID（留空表示群发）" style="width: 300px; margin-bottom: 10px" />
    <el-input v-model="message" placeholder="输入消息" style="width: 300px" @keyup.enter.native="send" />
    <el-button type="primary" @click="send">发送</el-button>
    <el-button type="success" @click="connect">连接WebSocket</el-button>
    <el-button type="danger" @click="disconnect">断开WebSocket</el-button>

    <el-divider>在线用户</el-divider>
    <div v-if="userList.length === 0">暂无在线用户</div>
    <el-tag
      v-for="user in userList"
      :key="user"
      type="info"
      @click="selectUser(user)"
    >
      {{ user }}
    </el-tag>

    <el-divider>消息记录</el-divider>
    <div v-for="(msg, index) in messages" :key="index">{{ msg }}</div>
  </div>
</template>

<script>
export default {
  name: 'WebSocketChatRoomSessionId',
  data() {
    return {
      ws: null,
      message: '',
      messages: [],
      toUserId: '',
      userList: []
    };
  },
  mounted() {
    this.connect();
  },
  beforeDestroy() {
    if (this.ws) this.ws.close();
  },
  methods: {
    connect() {
      this.ws = new WebSocket('ws://localhost:8080/websocket/chatRoomSessionId');

      this.ws.onopen = () => {
        this.messages.push('✅ WebSocket 连接成功');
      };

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'userList') {
            this.userList = data.users;
          } else if (data.type === 'message') {
            this.messages.push(`[${data.fromUserId || '系统'}]: ${data.content}`);
          }
        } catch (e) {
          this.messages.push(event.data);
        }
      };

      this.ws.onclose = () => {
        this.messages.push('❌ WebSocket 连接关闭');
      };

      this.ws.onerror = (err) => {
        this.messages.push('⚠️ WebSocket 连接异常');
        console.error(err);
      };
    },
    disconnect() {
      if (this.ws) {
        this.ws.close(1000, "用户主动断开");
        this.ws = null;
      }
    },
    send() {
      if (this.ws && this.message) {
        const payload = {
          type: this.toUserId ? 'private' : 'broadcast',
          toUserId: this.toUserId || null,
          content: this.message
        };
        this.ws.send(JSON.stringify(payload));
        this.message = '';
      } else {
        alert("未连接 WebSocket 或消息为空");
      }
    },
    selectUser(userId) {
      this.toUserId = userId;
    }
  }
};
</script>
